<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <div v-if="!isLoading && !isError">
            <el-button type="primary" size="large" @click="openDialog" circle>
              打卡
            </el-button>
            <HealthDialog :address="address" ref="healthDialogRef" />
          </div>
          <div v-else>
            <el-button type="danger" :disabled="true" size="large" circle>
              等待定位完成
            </el-button>
          </div>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card shadow="hover">
          <div class="state" v-if="!isLoading && !isError">
            <span>
              城市 - {{ location.address?.province }}-{{
                location.address?.city
              }}-{{ location.address?.district }}-{{ location.address?.street }}
            </span>
          </div>
          <div class="state" v-else-if="isError">
            出错了，请刷新下页面{{ status }}
          </div>
          <div class="state" v-else>定位中(请耐心等待一段时间)...</div>
          <button v-if="!isLoading" @click="get">重新获取</button>
          <BMap
            enableScrollWheelZoom
            ref="map"
            @initd="get"
            :center="location.point || undefined"
          >
            <template v-if="!isLoading">
              <BMarker :position="location.point"></BMarker>
              <BCircle
                strokeStyle="solid"
                strokeColor="#0099ff"
                :strokeOpacity="0.8"
                fillColor="#0099ff"
                :fillOpacity="0.5"
                :center="location.point"
                :radius="location.accuracy"
              />
            </template>
          </BMap>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useBrowserLocation } from 'vue3-baidu-map-gl'
import HealthDialog from './components/HealthDialog.vue'

// ------------------------------ 父子通信 ------------------------------
const healthDialogRef = ref()
const openDialog = () => {
  healthDialogRef.value.handleDialogVisible()
}

// ------------------------------ 地图 ------------------------------
const map = ref()
const { get, location, isLoading, isError, status } = useBrowserLocation(
  null,
  () => {
    map.value.resetCenter()
  }
)
// 计算地址
const address = computed((): string => {
  return isLoading
    ? location.value.address.province +
        location.value.address.city +
        location.value.address.district +
        location.value.address.street
    : ''
})
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
